package com.unisv.dj.util;

import java.util.Calendar;

import android.content.Context;
import android.database.ContentObserver;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.AttributeSet;

/**
 * 自定义DigitalClock输出格式
 * @author 农民伯伯
 *
 */
public class CountDownDigitalClock extends android.widget.DigitalClock {

    Calendar mCalendar;
    private final static String m12 = "h:mm aa";//h:mm:ss aa
    private final static String m24 = "k:mm";//k:mm:ss
    private FormatChangeObserver mFormatChangeObserver;

    private Runnable mTicker;
    private Handler mHandler;

    private boolean mTickerStopped = false;

    String mFormat;
    //add begin by fly
    private long mDeadtime;
    private DeadtimeListener mDeadtimeLister;
    //add end by fly
    public CountDownDigitalClock(Context context) {
        super(context);
        initClock(context);
    }

    public CountDownDigitalClock(Context context, AttributeSet attrs) {
        super(context, attrs);
        initClock(context);
    }

    private void initClock(Context context) {

        if (mCalendar == null) {
            mCalendar = Calendar.getInstance();
        }

        mFormatChangeObserver = new FormatChangeObserver();
        getContext().getContentResolver().registerContentObserver(
                Settings.System.CONTENT_URI, true, mFormatChangeObserver);

        setFormat();
    }

    @Override
    protected void onAttachedToWindow() {
        mTickerStopped = false;
        super.onAttachedToWindow();
        mHandler = new Handler();

        /**
         * requests a tick on the next hard-second boundary
         */
        mTicker = new Runnable() {
                public void run() {
                    if (mTickerStopped) return;
                    //mCalendar.setTimeInMillis(System.currentTimeMillis());
                    long mCurrentTime = System.currentTimeMillis();
                    //add begin by fly
                    if(mCurrentTime>=mDeadtime){
                    	mDeadtimeLister.onTimeEnd();
                    	return;
                    }
                    long mTimeDistance = mDeadtime - mCurrentTime;
                    if(mTimeDistance<=0){
                    	return;
                    }
                    int deadDays = getDeadDays(mTimeDistance);
                    int deadHour = getDeadHour(mTimeDistance);
                    int deadMinute = getDeadMinute(mTimeDistance);
                    int deadMills = getDeadMills(mTimeDistance);
                    String deadTimeStr = "距离活动结束还有"+deadDays+"天"+
													deadHour+"小时"+
								                    deadMinute+"分"+
								                    deadMills+"秒";
                    System.out.println(deadTimeStr);
                    //add end by fly
                    setText(deadTimeStr);
                    //setText(DateFormat.format(mFormat, mCalendar));
                    invalidate();
                    long now = SystemClock.uptimeMillis();
                    long next = now + (1000 - now % 1000);
                    mHandler.postAtTime(mTicker, next);
                }
            };
        mTicker.run();
    }
    //add begin by fly
    private int getDeadDays(long timeDistance){
    	return  (int) (timeDistance/(24*60*60*1000));
    }
    private int getDeadHour(long timeDistance){
    	int hour = (int)(timeDistance%(24*60*60*100))/(60*60*1000);
    	return hour;
    }
    private int getDeadMinute(long timeDistance){
    	int minute = 0;
    	minute = (int)(timeDistance%(24*60*60*100))%(60*60*1000)/(60*1000);
    	return minute;
    }
    private int getDeadMills(long timeDistance){
    	int mills = (int)(timeDistance%(24*60*60*100))%(60*60*1000)%(60*1000)/1000;
    	return mills;
    }
    //add end by fly
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mTickerStopped = true;
    }

    /**
     * Pulls 12/24 mode from system settings
     */
    private boolean get24HourMode() {
        return android.text.format.DateFormat.is24HourFormat(getContext());
    }

    private void setFormat() {
        if (get24HourMode()) {
            mFormat = m24;
        } else {
            mFormat = m12;
        }
    }

    private class FormatChangeObserver extends ContentObserver {
        public FormatChangeObserver() {
            super(new Handler());
        }

        @Override
        public void onChange(boolean selfChange) {
            setFormat();
        }
    }
    //add begin by fly
    /**
     * set the dead time
     * @param deadtime
     */
    public void setDeadtime(long deadtime){
    	this.mDeadtime = deadtime ;
    }
    public interface DeadtimeListener{
    	public void onTimeEnd();
    }
    public void setDeadtimeListener(DeadtimeListener deadtimeListener){
        this.mDeadtimeLister = deadtimeListener;
    }
    //add end by fly
}

//public class Main extends Activity {
//    /** Called when the activity is first created. */
//	private CountDownDigitalClock mClock ;
//    @Override
//    public void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.main);
//        mClock = (CountDownDigitalClock) findViewById(R.id.myClock);
//        mClock.setDeadtime(getDeadTimeFromServer());
//        mClock.setDeadtimeListener(new CountDownDigitalClock.DeadtimeListener() {
//			@Override
//			public void onTimeEnd() {
//				showToast("倒计时已结束！！！");
//			}
//		});
//    }
//    private long getDeadTimeFromServer(){
//    	long deadTime = 0 ;
//    	Calendar mCalendar = Calendar.getInstance();
//    	mCalendar.set(Calendar.DAY_OF_YEAR,4);
//    	mCalendar.set(Calendar.HOUR, 4);
//    	mCalendar.set(Calendar.MINUTE, 1);
//    	mCalendar.set(Calendar.MILLISECOND, 50);
//    	deadTime = mCalendar.getTimeInMillis();
//    	return deadTime;
//    }
//    private void showToast(String msg){
//    	Toast.makeText(this, msg, 1000).show();
//    }
//}
